/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.attachment.controller  
 */
package com.apache.attachment.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.apache.action.PlatFromAction;
import com.apache.api.manager.BaseManager;
import com.apache.api.vo.ResultMsg;
import com.apache.attachment.mommon.AttachmentConfig;
import com.apache.attachment.mommon.FileUtil;
import com.apache.attachment.mommon.ImageUtil;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.tools.StrUtil;

/**
 * description:  
 * @author mhguo 创建时间：2015-5-14  
 * @Copyright(c)2014:北京--软件技术有限公司
 */
@Controller
@RequestMapping("/attachment/media/")
public class UploadMediaAction extends PlatFromAction {
	/**
	 * description: 跳转到无实体附件上传页面
	 * @return  
	 * @author mhguo
	 * @update 2015-5-14
	 */
	/*@RequestMapping("toFileSample.action")
	public ModelAndView toFileSample(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("attachment/mvc/attachment-media-sample");
		return view;
	}*/

	/**
	 * description: 跳转到无实体图片上传页面
	 * @return  
	 * @author mhguo
	 * @update 2015-5-14
	 */
	/*@RequestMapping("toPicSample.action")
	public ModelAndView toPicSample(HttpServletRequest request) {
		ModelAndView view = new ModelAndView("attachment/mvc/pic-media-sample");
		return view;
	}*/

	/**
	 * description: 无实体单选按钮跳转方法 
	 * @author mhguo
	 * @update 2015-5-14
	 */
	@RequestMapping("toSample.action")
	public ModelAndView toSample(HttpServletRequest request) {
		ModelAndView view = null;
		String type = request.getParameter("type");
		if (Validator.isNull(type)) {
			view = new ModelAndView("error/error");
			view.addObject("errors", "缺少必要的参数，系统调用异常!");
			return view;
		}

		if ("0".equals(type)) {//跳转到无实体附件上传页面
			view = new ModelAndView("attachment/mvc/attachment-media-sample");
		} else if ("1".equals(type)) {//跳转到无实体图片上传页面
			view = new ModelAndView("attachment/mvc/pic-media-sample");
		} else if ("2".equals(type)) {//跳转到新无实体图片上传页面
			view = new ModelAndView("attachment/mvc/attachment-media-newsample");
		}
		return view;
	}

	/**
	 * 上传附件
	 */
	@RequestMapping("upload.action")
	public ModelAndView uploadMedia(@RequestParam("upload") CommonsMultipartFile upload, HttpServletRequest request) {
		ModelAndView view = new ModelAndView("attachment/mvc/attachment-upload-media");

		String uploadPath;//附件上传的目录
		String downloadUrl;//附件下载的地址
		String imaxLength = AttachmentConfig.getProp("IMAGE_MAX_LENGTH");//上传图片最大值，单位KB
		String fimaxLength = AttachmentConfig.getProp("FILE_MAX_LENGTH");//上传文件最大值，单位KB
		String allowType = AttachmentConfig.getProp("ALLOW_TYPE");//附件(文件、图片)允许类型
		String domain = AttachmentConfig.getProp("DOMAIN");//设置域
		String vmaxLength = AttachmentConfig.getProp("VIDEO_MAX_LENGTH");//上传视频最大值，单位MB
		String fmaxLength = AttachmentConfig.getProp("FLASH_MAX_LENGTH");//上传FLASH最大值，单位MB
		String allVidType = AttachmentConfig.getProp("ALLOW_VIDEO_TYPE");//允许的视频类型

		boolean re = false;//是否缩放图片

		String fileType = request.getParameter("fileType");//附件类型
		Integer imgW = Integer.parseInt(null == request.getParameter("imgW") ? "0" : request.getParameter("imgW"));//标准图宽度	
		Integer imgH = Integer.parseInt(null == request.getParameter("imgH") ? "0" : request.getParameter("imgH"));//标准图高度

		String callback = request.getParameter("callback");//是否有回调函数
		String idname = request.getParameter("idname");
		String isRemote = request.getParameter("isRemote");//是否跨域
		view.addObject("callback", callback);//回调函数名
		view.addObject("idname", idname);
		view.addObject("isRemote", isRemote);//是否跨域
		view.addObject("domain", domain);//域
		view.addObject("fileType", fileType);//附件类型

		logger.info("domain=" + domain + "; callback=" + callback + "; idname=" + idname + "; isRemote=" + isRemote);

		//附件非空验证
		if (upload == null) {
			view.addObject("flag", "F");
			view.addObject("msg", "请选择要上传的附件!");
			logger.info("请选择要上传的附件!");
			return view;
		}

		String uploadFileName = upload.getOriginalFilename();
		String uploadContentType = upload.getContentType();

		logger.info(upload.getName() + "  " + uploadFileName + "  " + uploadContentType);
		String nameEx = FileUtil.getInstance().getExtension(uploadFileName);//取得文件扩展名

		String alt = StrUtil.doNull(allowType).toUpperCase();//附件(文件、图片)允许类型
		String avt = StrUtil.doNull(allVidType).toUpperCase();//允许的视频类型
		String ft = StrUtil.doNull(fileType);//附件类型

		if ("pic".equalsIgnoreCase(fileType)) {//图片
			uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/pics/";
			downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/pics/";
		} else {//文件
			uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY") + "/atta/";
			downloadUrl = AttachmentConfig.getProp("DOWNLOAD_URL") + "/atta/";
		}

		if ("Attachment".equalsIgnoreCase(ft)) {
			if (upload.getSize() / 1024L > Long.valueOf(imaxLength).longValue()) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的附件大于 " + imaxLength + "KB,请处理后重新上传!");
				return view;
			}
			if ((StrUtil.isNotEmptyWithTrim(alt)) && (alt.indexOf(nameEx.toUpperCase()) == -1)) {
				view.addObject("flag", "F");
				view.addObject("msg", "不允许的附件类型!");
				return view;
			}
			re = true;
		} else if ("pic".equalsIgnoreCase(ft)) {

			/*if (upload.getSize() / 1024L < Long.valueOf(10).longValue()) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的图片小于 10KB,请处理后重新上传!");
				return view;
			}*/

			if (upload.getSize() / 1024 > Long.valueOf(imaxLength)) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的图片大于 " + imaxLength + "KB,请处理后重新上传!");
				return view;
			}
			if (StrUtil.isNotEmptyWithTrim(alt) && alt.indexOf(nameEx.toUpperCase()) == -1) {
				view.addObject("flag", "F");
				view.addObject("msg", "不允许的图片类型!");
				return view;
			}
			re = true;//允许缩放
		} else if ("video".equalsIgnoreCase(ft)) {
			if (upload.getSize() / 1048576L > Long.valueOf(vmaxLength).longValue()) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的视频大于 " + vmaxLength + "MB,请处理后重新上传!");
				return view;
			}
			if ((StrUtil.isNotEmptyWithTrim(avt)) && (avt.indexOf(nameEx.toUpperCase()) == -1)) {
				view.addObject("flag", "F");
				view.addObject("msg", "不允许的视频类型!");
				return view;
			}
		} else if ("flash".equalsIgnoreCase(ft)) {
			if (upload.getSize() / 1048576L > Long.valueOf(fmaxLength).longValue()) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的视频大于 " + fmaxLength + "MB,请处理后重新上传!");
				return view;
			}
			if ("SWF".indexOf(nameEx.toUpperCase()) == -1) {
				view.addObject("flag", "F");
				view.addObject("msg", "不允许的flash类型!");
				return view;
			}
		} else {

			/*if (upload.getSize() / 1024L < Long.valueOf(10).longValue()) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的文件小于 10KB,请处理后重新上传!");
				return view;
			}*/
			if (upload.getSize() / 1024L > Long.valueOf(fimaxLength).longValue()) {
				view.addObject("flag", "F");
				view.addObject("msg", "你的文件大于 " + fimaxLength + "KB,请处理后重新上传!");
				return view;
			}
			if ((StrUtil.isNotEmptyWithTrim(alt)) && (alt.indexOf(nameEx.toUpperCase()) == -1)) {
				view.addObject("flag", "F");
				view.addObject("msg", "不允许的文件类型类型!");
				return view;
			}

		}

		String cacDir;
		if ("pic".equals(fileType)) {
			cacDir = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + ft + "/";
		} else {
			cacDir = new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator;
		}

		String uplDir = uploadPath + File.separator + cacDir;//上传目录
		String dlUrl = downloadUrl + File.separator + cacDir;//下载目录
		File s = new File(uplDir);
		if (!s.exists()) {
			FileUtil.getInstance().makDir(uplDir);
		}
		String fileId = String.valueOf(System.currentTimeMillis());
		String wrFileName = fileId + "." + nameEx;
		String wrsFileName = fileId + ".s." + nameEx;

		//小图宽度		 
		Integer sImgW = Integer.parseInt(null == request.getParameter("sImgW") ? "0" : request.getParameter("sImgW"));
		//小图高度
		Integer sImgH = Integer.parseInt(null == request.getParameter("sImgH") ? "0" : request.getParameter("sImgH"));

		try {
			FileUtil.getInstance().writeFile(upload, uplDir + wrFileName);
		} catch (IOException e1) {
			logger.error("上传失败:" + e1);
			view.addObject("flag", "F");
			view.addObject("msg", "上传失败!!");
			return view;
		}

		if (re) {
			try {
				int iw = (imgW == null) ? 0 : imgW.intValue();
				int ih = (imgH == null) ? 0 : imgH.intValue();
				ImageUtil.getInstance().resize(uplDir + wrFileName, iw, ih);//标准图缩放

				int siw = (sImgW == null) ? 0 : sImgW.intValue();
				int sih = (sImgH == null) ? 0 : sImgH.intValue();
				if (siw != 0 || sih != 0) {
					FileUtil.getInstance().copy(new File(uplDir + wrFileName), new File(uplDir + wrsFileName));//创建小图
					ImageUtil.getInstance().resize(uplDir + wrsFileName, siw, sih);//小图缩放
				}
			} catch (BusinessException e) {
				logger.error("图片缩放失败:" + e);
				view.addObject("flag", "F");
				view.addObject("msg", "无效图片!!");
				return view;
			} catch (IOException e2) {
				logger.error("上传失败:" + e2);
				view.addObject("flag", "F");
				view.addObject("msg", "上传失败!!");
				return view;
			}

		}

		/*	request.setAttribute("domain", domain);
			request.setAttribute("idname", idname);
			request.setAttribute("isRemote", isRemote);
			request.setAttribute("fileType", fileType);
			request.setAttribute("flag", "T");
			request.setAttribute("callback", callback);
			request.setAttribute("murl", (dlUrl + wrFileName).replaceAll("\\\\", "/"));
			if ("pic".equals(fileType)) {
				request.setAttribute("surl", (dlUrl + wrsFileName).replaceAll("\\\\", "/"));
			}
			request.setAttribute("msg", "恭喜你，上传成功!!");*/

		view.addObject("flag", "T");
		view.addObject("murl", (dlUrl + wrFileName).replaceAll("\\\\", "/"));//标准图下载地址
		if ("pic".equals(fileType)) {
			view.addObject("surl", (dlUrl + wrsFileName).replaceAll("\\\\", "/"));//小图下载地址
		}
		view.addObject("msg", "恭喜你，上传成功!!");
		logger.info("domain=" + domain + "; callback=" + callback + "; idname=" + idname + "; isRemote=" + isRemote
				+ "; murl=" + (dlUrl + wrFileName).replaceAll("\\\\", "/") + "; fileType=" + fileType);
		return view;
	}

	@RequestMapping("delete.action")
	@ResponseBody
	public ResultMsg delete(HttpServletRequest request, String id) {
		ResultMsg rmsg = new ResultMsg();

		String attaFilePath = request.getParameter("attaFilePath");//文件路径
		String attafileName = request.getParameter("attafileName");//文件名称

		if (Validator.isNull(attaFilePath) || Validator.isNull(attafileName)) {
			rmsg.setFlag("F");
			rmsg.setMsg("缺少必要的参数！");
			return rmsg;
		}

		String uploadPath = AttachmentConfig.getProp("UPLOAD_DIRECTORY");
		if (StrUtil.isEmptyWithTrim(uploadPath)) {
			uploadPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
		}
		String uploadDir = uploadPath + File.separator + attaFilePath + File.separator + attafileName;

		File file = new File(uploadDir);
		if (file.exists()) {
			boolean ob = file.delete();
			if (ob) {
				rmsg.setFlag("T");
				rmsg.setMsg("操作成功！");
			} else {
				rmsg.setFlag("F");
				rmsg.setMsg("操作失败！");
			}
		} else {
			rmsg.setFlag("T");
			rmsg.setMsg("没有找到附件！");
		}

		return rmsg;
	}

	@Override
	protected Object data(HttpServletRequest arg0, String arg1, String arg2) {
		return null;
	}

	@Override
	protected BaseManager getBaseManager() {
		return null;
	}

	@Override
	protected String getPrefix() {
		return null;
	}

}
